package org.wannatrak.android.service;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.entity.BaseEntity;
import org.wannatrak.android.entity.TrackCounter;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-06-17 13:55:01 +0000 (Fri, 17 Jun 2011) $ 10:56 AM
 * @version: $Revision: 12 $
 * @id: $Id: TrackCounterService.java 12 2011-06-17 13:55:01Z sinyagovsky@gmail.com $
 */
public class TrackCounterService {

    private Context context;

    public TrackCounterService(Context context) {
        this.context = context;
    }

    public long getCurrentValue() {
        Cursor c = null;
        try {
            c = ApplicationContext.getDatabaseHelper().executeRawSQL("select max(" + BaseEntity._ID + ") as "
                    + BaseEntity._ID + " from " + TrackCounter.CONTENT_DIRECTORY, null);
            if (c.moveToFirst()) {
                return c.getLong(c.getColumnIndex(BaseEntity._ID));
            }
            return 0L;
        } finally {
            if (c != null) {
                c.close();
            }
        }
    }

    public long incValue() {
        ContentValues cv = new ContentValues();
        cv.put(BaseEntity._ID, (Long) null);
        Uri uri = context.getContentResolver().insert(TrackCounter.CONTENT_URI, cv);
        return ContentUris.parseId(uri);
    }
}
